package com.example.javabasic.thread.classone.demo3;

/**
 * 强制关闭线程: 通过父线程守护线程的特性  关闭业务线程
 */
public class ThreadService {
    //定义一个守护线程
    private Thread executeThread;

    public static void main(String[] args) {
        ThreadService threadService = new ThreadService();
        threadService.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("开始执行线程:" + Thread.currentThread().getName());

                Boolean bool = true;
                while (bool) {
                    try {
                        Thread.sleep(500);
                        System.out.println(1);
                    } catch (InterruptedException e) {
                        //休眠, 减少cpu消耗
                    }
                }
                System.out.println("线程执行完成");
            }
        });

        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    //执行线程
    public void execute(Runnable runnable) {
        //创建一个守护线程
        executeThread = new Thread(() -> {
            System.out.println("创建子线程");
            Thread runner = new Thread(runnable, "子线程");
            runner.start();
        }, "守护线程");
        executeThread.setDaemon(true);
        executeThread.start();
        System.out.println("启动线程:"+executeThread.getName());

    }

    /**
     * 关闭线程方法
     */
    public void shutDown() {
        //关闭线程
        executeThread.interrupt();
    }
}
